package com.dream.service.user.impl;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.dream.common.toolkits.http.HttpClientUtil;
import com.dream.common.toolkits.util.SHA1;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import sun.security.provider.MD5;

import java.util.ArrayList;
import java.util.List;

/**
 * 环信工具
 */
public class EasemobTools {

    /**
     *  通过用户Pin注册环信账号
     *  账号名与主站pin保持一致
     */
    public static boolean signUpSigleEasemobUser(String pin, String nickname) throws Exception {
        HttpClient httpClient = HttpClientUtil.getClient();
        //String url = "https://a1.easemob.com/1466180424068182/kefuchannelapp54105/users";
        String url = "https://a1.easemob.com/easemob-demo/chatdemoui/users";
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        JSONObject bodyJSON = new JSONObject();
        bodyJSON.put("username", pin);
        bodyJSON.put("password", SHA1.MD5Encode(pin));
        bodyJSON.put("nickname", StringUtils.isBlank(nickname) ? pin : nickname);
        StringEntity bodyEntity = new StringEntity(bodyJSON.toJSONString());
        post.setEntity(bodyEntity);
        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        String context = EntityUtils.toString(entity);
        JSONObject contextJSON = JSONObject.parseObject(context);
        if (contextJSON.containsKey("entities")) {
            return true;
        } else {
            System.out.println("Pin : " + pin + "; Create Easemob User Fail ：" + contextJSON.getString("error"));
            return false;
        }
    }

    public static void main(String[] args) {
        try {
            signUpSigleEasemobUser("dfaekefhejafjkjakf", "我是xiaojie");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
